package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.queryObject.TravelQueryObject;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.vo.TravelCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository travelRepository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IDestinationService destinationService;

    @Override
    public void save(Travel travel) {
        travel.setId(null);
        travelRepository.save(travel);
    }

    @Override
    public void update(Travel travel) {
        travelRepository.save(travel);
    }

    @Override
    public void delete(String id) {
        travelRepository.deleteById(id);
    }

    @Override
    public Travel get(String id) {
        Optional<Travel> travel = travelRepository.findById(id);

        if (travel.isPresent()){// 如果对应id的游记存在的话
            Travel travel1 = travel.get();
            travel1.setDest(destinationService.get(travel1.getDestId()));
            travel1.setAuthor(userInfoService.get(travel1.getUserId()));
            return travel1;
        }
        return null;
    }

    @Override
    public List<Travel> list() {
        List<Travel> all = travelRepository.findAll();
        return all;
    }

    @Override
    public Page<Travel> query(TravelQueryObject qo) {

        // 封装查询条件
        Query query = new Query();

        int[] arr = {0,1,2,3};

        for (int i : arr) {
            if (qo.getState()==i){
                query.addCriteria(Criteria.where("state").is(qo.getState()));
            }
        }

        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }

        TravelCondition dayType = qo.getDayType();
        TravelCondition perExpendType = qo.getPerExpendType();
        /*TravelCondition goDayType = qo.getGoDayType();*/
        if (dayType!=null){
            query.addCriteria(Criteria.where("day").gte(dayType.getMin()).lte(dayType.getMax()));
        }
        if (perExpendType!=null){
            query.addCriteria(Criteria.where("perExpend").gte(perExpendType.getMin()).lte(perExpendType.getMax()));
        }
        /*if (dayType!=null){
            query.addCriteria(Criteria.where("day").gte(goDayType.getMin()).lte(goDayType.getMax()));
        }*/

        // 总条数
        long totalCount = template.count(query, Travel.class);

        // 如果总条数为0 , 那么返回空的分页对象
        if (totalCount==0){
            return Page.empty();
        }

        // 分页对象 , 参数1为当前页 从0开始 , 参数2为每页显示条数 , 参数3为排序方式, 参数4为按哪个字段排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                Sort.Direction.ASC,"_id");

        if (qo.getOrderType()==qo.ORDER_NEW){//按最新排列
            pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                    Sort.Direction.DESC,"createTime");
        }
        if (qo.getOrderType()==qo.ORDER_HOT){//按最新排列
            pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                    Sort.Direction.DESC,"viewnum");
        }


        query.with(pageable);// 添加查询条件

        List<Travel> list = template.find(query, Travel.class);

        for (Travel travel : list) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }

        // PageImpl 为 Page 接口的一个实现类

        return new PageImpl<>(list, pageable,totalCount );
    }

    @Override
    public void changeState(TravelQueryObject qo) {

        Travel travel = travelRepository.findById(qo.getId()).orElse(null);
        travel.setState(qo.getState());

        if (qo.getState() == Travel.STATE_RELEASE){
            //如果是2则表示是通过审核
            //需要设置发布的时间和更新的时间
            travel.setReleaseTime(new Date());
            travel.setLastUpdateTime(new Date());
        }else {
            //除了审核通过以外的状态都不应该有发布时间
            travel.setReleaseTime(null);
            travel.setLastUpdateTime(new Date());
        }

        travelRepository.save(travel);

    }

    @Override
    public List<Travel> queryViewnumTop3ByDestId(String destId) {

        List<Travel> travels = travelRepository.findByDestIdOrderByViewnum(destId);
        List<Travel> travels1 = new ArrayList<>();
        if (travels.size()>=3){
            travels1 = travels.subList(0, 3);
        }
        return travels1;
    }

    @Override
    public void saveOrUpdate(Travel travel) {

        //设置目的地名称
        travel.setDestName(destinationService.get(travel.getDestId()).getName());


        if (StringUtils.hasLength(travel.getId())){
            //如果有id进行编辑操作

            //先查再更新
            Travel temp = this.get(travel.getId());

            travel.setCreateTime(temp.getCreateTime());
            travel.setLastUpdateTime(new Date());

            travel.setViewnum(temp.getViewnum());
            travel.setReleaseTime(temp.getReleaseTime());
            travel.setFavornum(temp.getFavornum());
            travel.setSharenum(temp.getSharenum());
            travel.setThumbsupnum(temp.getThumbsupnum());

            this.update(travel);
        }else {
            //如果没有id进行新增操作
            //游记创建时间
            travel.setCreateTime(new Date());
            //最后更新时间设置为空
            travel.setLastUpdateTime(new Date());
            this.save(travel);
        }
    }

}
